<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.userName"
        placeholder="机构名称搜索"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />&nbsp;&nbsp;&nbsp;
      <el-select
        v-model="listQuery.state"
        clearable
        placeholder="状态"
        style="width: 200px;"
        class="filter-item"
      >
        <!-- <el-option :value="0" label="全部">全部</el-option> -->
        <el-option :value="0" label="开启">开启</el-option>
        <el-option :value="1" label="关闭">关闭</el-option> </el-select
      >&nbsp;&nbsp;&nbsp;
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <br />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="机构名称" prop="id" align="center" width="260">
        <template slot-scope="{ row }">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="APP展示名称" class-name="status-col" width="260">
        <template slot-scope="{ row }">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="服务天数" class-name="status-col" width="260">
        <template slot-scope="{ row }">
          <span>{{ row.serviceDays }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当天服务人数" class-name="status-col" width="260">
        <template slot-scope="{ row }">
          <span>{{ row.serviceNumber }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="登录状态"
        align="center"
        min-width="120"
        class-name="small-padding"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.limitSwitch"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            align="center"
            @change="changeVisitStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="推送状态"
        align="center"
        min-width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.pushSwitch"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            align="center"
            @change="changeStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="短信通知"
        align="center"
        min-width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.pageSwitch"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            align="center"
            @change="changePageSwitch(row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="负责人通知"
        align="center"
        min-width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.leadSwitch"
            active-text="开"
            inactive-text="关"
            active-color="#13ce66"
            inactive-color="#ff4949"
            align="center"
            @change="changeLeadSwitch(row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="260"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="info" size="mini" @click="addBatch(row)">
            添加协议
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="warning" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="loanList"
    />

    <!-- <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loan.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loan.password" type="password" />
        </el-form-item>
        <el-form-item label="展示名称" prop="nickName">
          <el-input v-model="loan.nickName" />
        </el-form-item>
        <el-form-item label="服务天数" prop="serviceDays">
          <el-input v-model="loan.serviceDays" />
        </el-form-item>
        <el-form-item label="当天服务人数" prop="serviceNumber">
          <el-input v-model="loan.serviceNumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog> -->

    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="机构名称" prop="userName">
          <el-input v-model="loan.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loan.password" type="password" />
        </el-form-item>
        <el-form-item label="APP展示名称" prop="nickName">
          <el-input v-model="loan.nickName" />
        </el-form-item>
        <el-form-item label="logo">
          <el-upload
            ref="upload"
            :action="action"
            limit="1"
            :auto-upload="true"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人手机号">
          <el-input v-model="loan.phonenumber" />
        </el-form-item>
        <!-- <el-form-item label="服务天数" prop="serviceDays">
          <el-input v-model="loan.serviceDays" />
        </el-form-item>
        <el-form-item label="当天服务人数" prop="serviceNumber">
          <el-input v-model="loan.serviceNumber" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="createData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

        <el-dialog title="编辑" :visible.sync="dialogFormVisible2">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="loan1"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="机构名称" prop="userName">
          <el-input v-model="loan1.userName" readonly/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loan1.password" type="password" />
        </el-form-item>
        <el-form-item label="App展示名称" prop="nickName">
          <el-input v-model="loan1.nickName" />
        </el-form-item>
         <el-form-item label="logo">
          <el-upload
            ref="upload"
            :action="action"
            limit="1"
            :auto-upload="true"
            :on-success="handleSuccess1"
            :on-error="handleError"
            :file-list="fileList"
            :show-file-list="false"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人手机号">
          <el-input v-model="loan1.phonenumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel2()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加协议" :visible.sync="dialogFormVisible1" :before-close="cancel1">
      <el-form
        ref="form"
        :rules="formRules"
        :inline="true"
        :model="form"
        label-width="80px"
      >
        <div v-for="(item, index) in form.dynamicItem" :key="index">
          <el-form-item
            label="协议名称"
            :prop="'dynamicItem.' + index + '.protocolName'"
            :rules="{
              required: true,
              message: '协议名称不能为空',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.protocolName"></el-input>
          </el-form-item>
          <el-form-item
            label="协议链接"
            :prop="'dynamicItem.' + index + '.protocolUrl'"
            :rules="{
              required: true,
              message: '协议链接不能为空',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.protocolUrl"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="deleteItem(item, index)" v-show="index!=0">删除</el-button>
          </el-form-item>
           <el-button @click="addItem" type="primary">增加</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">
          取消
        </el-button>
        <el-button type="primary" @click="submitBatch">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { addloan, deleteById, editloan, loanList } from "@/api/sys";
import { getList, addList, update, remove, addBatch,findList} from "@/api/advertising";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { list } from '@/api/deploy';
export default {
  name: "Sysloanlist",
  components: { Pagination },
  directives: { waves },
  data() {
    var checkhttp = (rule, value, callback) => {
      var reg = /^http:\/\//;
      var regs = /^https:\/\//;
      if (reg.test(value)) {
        callback();
      } else {
        if (!regs.test(value)) {
          callback(new Error("需要https://开头"));
        } else {
          callback();
        }
      }
    };
    return {
      action: process.env.VUE_APP_BASE_API.split('/')[0] + '//' + process.env.VUE_APP_BASE_API.split('/')[2] + '/api/foundation/api/file/upload',
      form: {
        protocolName: "",
        protocolUrl: "",
        dynamicItem: [
          // { crmId: 0, crmNickname: "", protocolName: "", protocolUrl: "",crmType:1},
        ],
      },
      smsNotice: false,
      limitNum: 1,
      fileList: [],
      comment: "",
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        avatar: "",
        current: 1,
        nickName: "",
        password: "",
        phonenumber: "",
        remark: "",
        size: 10,
        state: "",
        userName: "",
      },
      loan: {
        avatar: "",
        createBy: "",
        createTime: "",
        delFlag: "",
        deptId: 0,
        loginDate: "",
        loginIp: "",
        nickName: "",
        password: "",
        phonenumber: "",
        pushState: 0,
        remark: "",
        smsNotice: 0,
        status: "",
        updateBy: "",
        updateTime: "",
        userId: 0,
        userName: "",
        userType: "",
        serviceNumber: "",
        serviceDays: "",
      },
      loan1: {
        avatar: "",
        createBy: "",
        createTime: "",
        delFlag: "",
        deptId: 0,
        loginDate: "",
        loginIp: "",
        nickName: "",
        password: "",
        phonenumber: "",
        pushState: 0,
        remark: "",
        smsNotice: 0,
        status: "",
        updateBy: "",
        updateTime: "",
        userId: 0,
        userName: "",
        userType: "",
        serviceNumber: "",
        serviceDays: "",
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "新增",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userName: [{ required: true, message: "名称必填", trigger: "blur" }],
        password: [{ required: true, message: "密码必填", trigger: "blur" }],
        nickName: [
          { required: true, message: "展示名称必填", trigger: "blur" },
        ],
        serviceDays: [
          { required: true, message: "服务天数必填", trigger: "blur" },
        ],
        serviceNumber: [
          { required: true, message: "当天服务人数必填", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      listLoading: false,
      imageUrl: "",
      pushState: false,
      status: false,
      leadSwitch:false
    };
  },
  created() {
    this.loanList();
  },
  methods: {
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error(err.msg)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleSuccess(res, file, fileList) {
      this.loan.avatar = res.data // 服务器返回的文件地址
      this.fileList[0] = file
      this.imageUrl = res.data
      this.$message({
        message: '文件上传成功',
        type: 'success'
      })
      this.$refs.upload.clearFiles()// 清楚上次上传记录
    },
    handleSuccess1(res, file, fileList) {
      this.loan1.avatar = res.data // 服务器返回的文件地址
      this.fileList[0] = file
      this.imageUrl = res.data
      this.$message({
        message: '文件上传成功',
        type: 'success'
      })
      this.$refs.upload.clearFiles()// 清楚上次上传记录
    },
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      })
    },
    cancel1() {
      this.form.dynamicItem= [
          // { crmId: 0, crmNickname: "", protocolName: "", protocolUrl: "",crmType:1 },
        ],
      this.dialogFormVisible1 = false;
    },
    async addBatch(row) {
      const res = await findList({ crmId: row.userId,crmType:1 });
      if(res.data.code == 200){
        let listData=res.data.data
       if(listData.length==0){
        this.form.dynamicItem= [
          { crmId: 0, crmNickname: "", protocolName: "", protocolUrl: "",crmType:1},
        ];
       }else{
         listData.forEach((item)=>{
          this.form.dynamicItem.push(item)
        })
       }
      }
      this.dialogFormVisible1 = true;
      this.form.dynamicItem[0].crmId = row.userId;
      this.form.dynamicItem[0].crmNickname = row.nickName;
    },
    submitBatch() {
      addBatch(this.form.dynamicItem).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "添加成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$notify({
            title: "fail",
            message: res.data.msg,
            type: "fail",
            duration: 2000,
          });
        }
        this.cancel1()
      });
    },
    addItem() {
      this.form.dynamicItem.push({
        crmId: this.form.dynamicItem[0].crmId,
        crmNickname: this.form.dynamicItem[0].crmNickname,
        crmType:1,
        protocolName: "",
        protocolUrl: "",
      });
    },
    deleteItem(item, index) {
      this.form.dynamicItem.splice(index, 1);
    },
    tableRowClassName({ row }) {
      if (row.unique >= row.queryLimit * 0.75) {
        return "borderRed";
      }
      return "";
    },
    changeVisitStatus(row) {
      this.loan = row;
      if (this.loan.limitSwitch) {
        this.loan.status = 0;
      } else {
        this.loan.status = 1;
      }
      update(this.loan).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          this.loanList(this.listQuery);
        } else {
          this.$notify({
            title: "fail",
            message: "更新失败",
            type: "fail",
            duration: 2000,
          });
        }
      });
    },

    changeStatus(row) {
      this.loan = row;
      // 贷款详情页开关0-关，1-开
      if (this.loan.pushSwitch) {
        this.loan.pushState = 1;
      } else {
        this.loan.pushState = 0;
      }
      update(this.loan).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          this.loanList(this.listQuery);
        } else {
          this.$notify({
            title: "fail",
            message: "更新失败",
            type: "fail",
            duration: 2000,
          });
        }
      });
    },
    changePageSwitch(row) {
      this.loan = row;
      if (this.loan.pageSwitch) {
        this.loan.smsNotice = 1;
      } else {
        this.loan.smsNotice = 0;
      }
      update(this.loan).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          this.loanList(this.listQuery);
        } else {
          this.$notify({
            title: "fail",
            message: "更新失败",
            type: "fail",
            duration: 2000,
          });
        }
      });
    },
    changeLeadSwitch(row){
      this.loan = row;
      if (this.loan.leadSwitch) {
        this.loan.leadNotice = 1;
      } else {
        this.loan.leadNotice = 0;
      }
      update(this.loan).then((res) => {
        if (res.data.code === 200) {
          this.$notify({
            title: "Success",
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          this.loanList(this.listQuery);
        } else {
          this.$notify({
            title: "fail",
            message: "更新失败",
            type: "fail",
            duration: 2000,
          });
        }
      });
    },
    // 获取列表
    async loanList(listQuery) {
      const res = await getList(this.listQuery);
      res.data.data.records.forEach((element) => {
        element.pageSwitch = element.smsNotice === 1;
        element.pushSwitch = element.pushState === 1;
        element.limitSwitch = element.status == 0;
        element.leadSwitch=element.leadNotice==1
      });
      this.tableData = res.data.data.records;
      this.total = res.data.data.total;
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.loanList(this.listQuery);
    },
    cancel() {
      this.dialogFormVisible = false;
      this.loanList();
    },
     cancel2() {
      this.dialogFormVisible2 = false;
      this.loanList();
    },

    handleCreate() {
      this.dialogFormVisible = true;
      this.loan.userName="";
      this.loan.password="";
      this.loan.nickName="";
      this.loan.phonenumber=""
      this.imageUrl="";
      this.loan.avatar="";
      this.fileList=[]
      // 刷新表单数据验证提示
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      const that = this;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addList(this.loan).then((res) => {
            if (res.data.code === 200) {
              that.$notify({
                title: "Success",
                message: "新增成功",
                type: "success",
                duration: 2000,
              });
              that.loanList(that.listQuery);
            } else {
              this.$notify({
                title: "fail",
                message: res.data.msg,
                type: "fail",
                duration: 2000,
              });
            }
            this.dialogFormVisible = false;
          });
        }
      });
    },
    async handleUpdate(row) {
      this.smsNotice = row.smsNotice === 1;
      this.loan1 = row;
      this.imageUrl=row.avatar;
      this.dialogFormVisible2 = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      const that = this;
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          update(that.loan1).then((res) => {
            //
            if (res.data.code === 200) {
              that.$notify({
                title: "Success",
                message: "编辑成功",
                type: "success",
                duration: 2000,
              });
              that.loanList(that.listQuery);
            } else {
              that.$notify({
                title: "fail",
                message: res.data.msg,
                type: "fail",
                duration: 2000,
              });
            }
            this.dialogFormVisible2 = false;
          });
        }
      });
    },
    handleDelete(row, index) {
      var that = this;
      this.$confirm("删除提示！", "确认删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        remove({ id: row.userId }).then((res) => {
          if (res.data.code === 200) {
            that.$notify({
              title: "Success",
              message: "删除成功",
              type: "success",
              duration: 2000,
            });
            that.loanList(that.listQuery);
          } else {
            this.$notify({
              title: "错误",
              message: res.data.msg,
              type: "fail",
              duration: 2000,
            });
          }
        });
      });
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>

<style scoped>
.pic {
  width: 150px;
  margin-top: 10px;
  margin-left: 10px;
}
.ok {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(35, 248, 124);
}
.fail {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(240, 174, 76);
}
.info {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
}
.info-name {
  margin-left: 50px;
  margin-top: 10px;
  color: rgb(172, 176, 177);
}
.title {
  margin-top: 10px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 400;
}
.box {
  margin-top: 10px;
  width: 100%;
  border: solid rgb(138, 219, 230) 2px;
}
.nick {
  font-size: 30px;
  font-weight: 600;
}
.link-top {
  margin-left: 10px;
  margin-top: 10px;
  width: 100%;
  height: 2px;
  border-top: solid rgb(138, 219, 230) 2px;
}
.link-title {
  margin-left: 10px;
  margin-top: 10px;
  width: 80px;
  height: 2px;
  border-top: solid rgb(172, 176, 177) 2px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
